<template>
  <view class="location-page">

  </view>
</template>

<script>
  import {
    createOrder,
    callPayment,
    getAddressByLatAndLon
  } from "./api/pay.js";
  import {
    getAuthCode
  } from "@/common/util.js"
  export default {
    data() {
      return {
        orderParams: {}
      };
    },
    async onLoad(options) {
      uni.hideHomeButton()
      this.orderParams = wx.getStorageSync("orderParams") || {}
      this.orderParams.orderNo = options.orderNo
      let r = await getAuthCode();
      this.orderParams.authCode = r.code;
      this.getLocation();
    },
    methods: {
      getLocation() {
        uni.showLoading({
          title: '支付中'
        });
        uni.getLocation({
          // #ifdef MP-WEIXIN
          type: 'wgs84',
          // #endif
          success: async (res) => {
            const longitude = Number(res.longitude).toFixed(4),
              latitude = Number(res.latitude).toFixed(4);
            try {
              let resData = await getAddressByLatAndLon(latitude, longitude)
              const province = resData.addressComponent.province; // 省份
              const city = resData.addressComponent.city; // 城市
              this.orderParams.gpsFlag = '1';
              this.orderParams.info = `${longitude},${latitude}`;
              this.orderParams.prov = province;
              this.orderParams.city = city
              uni.hideLoading();
              this.placeOrder()
            } catch (e) {
              uni.hideLoading();
              uni.redirectTo({
                url: `/pages/iassCashier/error?errMsg=${e.errMsg}${e.statusCode}`
              })
            }
          },
          fail: (res) => {
            this.orderParams.gpsFlag = '1';
            this.orderParams.info = '';
            this.orderParams.prov = '';
            this.orderParams.city = ''
            uni.hideLoading();
            this.placeOrder()
          }
        });
      },
      // 下单支付
      async placeOrder() {
        try {
          const res = await createOrder(this.orderParams),
            payWay = this.orderParams.payWay;
          if (payWay != '1' && payWay != '2') {
            let urlKey = payWay == '13' ? 'returnUrl' : 'payUrl';
            let encodedReturnUrl = encodeURIComponent(res[urlKey]);
            uni.redirectTo({
              url: `/pages/iassCashier/payView?url=${encodedReturnUrl}`
            })
          } else {
            callPayment(res)
          }
        } catch (e) {
          this.$toast(e.respMsg)
        }
      },
    }
  }
</script>

<style lang="scss" scoped>
  .location-page {
    min-height: 100vh;
    background-color: #fff;
  }
</style>